package com.xy.cloud.config;

import com.xy.cloud.controller.OrderController;
import com.xy.cloud.domain.entities.RocketmqTransactionLog;
import com.xy.cloud.service.OrderService;
import com.xy.cloud.service.RocketmqTransactionLogService;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

@RocketMQTransactionListener
public class RocketMQTransactionListenter implements RocketMQLocalTransactionListener {

    private static final Logger log = LoggerFactory.getLogger(RocketMQTransactionListenter.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private RocketmqTransactionLogService rocketmqTransactionLogService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("==========执行本地事务==========");
        MessageHeaders headers = message.getHeaders();
        //获取事务ID
        String transactionId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);
        String orderId = (String)headers.get("order_id");
        log.info("transactionId is {}, orderId is {}",transactionId,orderId);

        try{
            //执行本地事务，并记录日志
            orderService.changeStatuswithRocketMqLog(orderId, transactionId);
            //执行成功，可以提交事务
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        MessageHeaders headers = message.getHeaders();
        //获取事务ID
        String transactionId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);
        log.info("检查本地事务,事务ID:{}",transactionId);
        //根据事务id从日志表检索
        RocketmqTransactionLog rocketmqTransactionLog = rocketmqTransactionLogService.lambdaQuery().eq(RocketmqTransactionLog::getTransactionId, transactionId).one();
        if(null != rocketmqTransactionLog){
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
